<template>
  <Card>
    <Row type="flex"
         align="top"
         justify="space-between">
      <Form ref="formSearch"
            class="sellPending"
            inline>
        <FormItem label="场馆"
                  v-if="!userInfo.storeId">
          <Select v-model="formSearch.storeId"
                  style="width:150px"
                  clearable>
            <Option v-for="(item, index) in storeIdList"
                    :key="index"
                    :value="item.id">{{item.storeName}}</Option>
          </Select>
        </FormItem>
        <FormItem label="卡名称">
          <Select v-model="formSearch.cardName"
                  style="width:200px"
                  filterable
                  remote
                  clearable
                  :remote-method="remoteMethod1"
                  :loading="loading1"
                  placeholder="输入卡名称筛选">
            <Option v-for="(option, index) in options1"
                    :value="option.label"
                    :key="index">{{option.label}}</Option>
          </Select>
        </FormItem>
        <FormItem label="累计消费范围">
          <Poptip trigger="focus">
            <Input v-model="formSearch.moneyMin"
                   prefix="logo-usd"
                   placeholder="起始"
                   style="width: 120px" />
            <div slot="content">{{ formatStartNumber }}</div>
          </Poptip>
        </FormItem>
        <FormItem label=" -">
          <Poptip trigger="focus">
            <Input v-model="formSearch.moneyMax"
                   prefix="logo-usd"
                   placeholder="结束"
                   style="width: 120px" />
            <div slot="content">{{ formatEndNumber }}</div>
          </Poptip>
        </FormItem>

        <FormItem label="手机/姓名">
          <Row>
            <Col span="18">
            <Input clearable
                   placeholder="输入手机/姓名搜索"
                   class="search-input"
                   v-model="formSearch.member" />
            </Col>
            <Col span="4"
                 offset="1">
            <Button @click="expenseList"
                    class="search-btn"
                    type="primary">
              <Icon type="search" />搜索</Button>
            </Col>
          </Row>

        </FormItem>
      </Form>
      <Button class="margin-b-20"
              icon="md-add"
              type="primary"
              @click="expenseModal = true">添加消费记录</Button>
    </Row>
    <Table border
           :loading="tableLoading"
           :columns="expenseListColumns"
           :data="expenseColumns">
    </Table>
    <Row type="flex"
         class="margin-t-20">
      <Page :total="pageTotal"
            @on-change="changePage" />
    </Row>
    <br>
    <Button type="primary"
            v-if="!userInfo.storeId"
            size="large"
            @click="exportExpense">
      <Icon type="ios-download-outline"></Icon> 导出数据
    </Button>
    <Modal v-model="expenseModal"
           title="添加消费记录"
           :loading="loading"
           :mask-closable="false"
           @on-ok="onExpenseSubmit"
           @on-visible-change="onAddExpenseVisible">
      <Form :model="expense"
            ref="expenseForm"
            :rules="ruleValidate"
            :label-width="100">
        <FormItem label="手机"
                  prop="member">
          <Input v-model="expense.member"
                 style="width:300px"
                 search
                 enter-button
                 @on-search="getByPhone"
                 placeholder="输入手机号码查找用户信息" />
          <span class="demo-data">{{seachText}}</span>
        </FormItem>
        <FormItem label="场馆"
                  v-if="!userInfo.storeId">
          <Select v-model="expense.storeId"
                  style="width:300px"
                  clearable>
            <Option v-for="(item, index) in storeIdList"
                    :key="index"
                    :value="item.id">{{item.storeName}}</Option>
          </Select>
        </FormItem>
        <FormItem label="卡名称"
                  prop="cardName">
          <Select clearable
                  v-model="expense.cardId"
                  @on-change="changeCardType"
                  style="width:300px">
            <Option v-for="(item, index) in seachInfoCards"
                    :value="item.id"
                    :key="index">{{ item.cardName }}--余额：{{ item.cardCount }}{{expense.consumptionType | cardTypeUt}}</Option>
          </Select>

        </FormItem>

        <FormItem label="消费"
                  prop="consumption">
          <Input v-model="expense.consumption"
                 style="width: 300px;">
          <div slot="append">
            <span v-if="expense.consumptionType === 1">天</span>
            <span v-if="expense.consumptionType === 2">次</span>
            <span v-if="expense.consumptionType === 3">元</span>
          </div>
          </Input>
        </FormItem>
        <FormItem label="备注">
          <Input v-model="expense.remarks"
                 clearable
                 maxlength="100"
                 show-word-limit
                 type="textarea"
                 placeholder="请输入备注"
                 style="width: 300px" />
        </FormItem>
      </Form>
    </Modal>

    <Modal title="会员详情"
           :mask-closable="false"
           fullscreen
           scrollable
           v-model="detailsModal">
      <member-details ref="detailsModal"></member-details>
      <div slot="footer">
        <Button type="error"
                size="large"
                long
                @click="detailsModal = false">关闭</Button>
      </div>
    </Modal>
  </Card>

</template>
<script>
import memberDetails from '../members/components/member-details'
import { expenseList, addExpense, exportExpense, deleteExpense, getMemberCard } from '@/api/expense'
import { getByPhone } from '@/api/user'
import { cardList } from '@/api/setting-course'
import { storeAll } from '@/api/setting-shop'
import { mapActions, mapGetters } from 'vuex'
import { formatDateTime } from '@/libs/util'

export default {
  components: {
    memberDetails
  },
  data () {
    return {
      detailsModal: false,
      expenseModal: false,
      loading: true,
      tableLoading: false,
      // 弹框
      expense: {
        storeId: '',
        cardId: '',
        consumption: '',
        consumptionType: 1,
        member: '',
        remarks: ''
      },
      // 会员卡列表
      cardNameList: [],
      storeIdList: [],
      // 会员卡对象
      cardNameObj: {},
      // 个人会员卡对象
      myCardNameObj: {},
      // 消费会员卡信息
      seachInfoCards: [],
      seachText: '',
      ruleValidate: {
        cardId: [{ required: true, type: 'number', message: '请选择会员卡', trigger: 'blur' }],
        member: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
        consumption: [{ required: true, message: '请输入消费金额/次数', trigger: 'blur' }]
      },
      pageTotal: 0,
      expenseListColumns: [
        {
          title: '姓名',
          key: 'name',
          fixed: 'left',
          minWidth: 100
        },
        {
          title: '电话',
          key: 'phone',
          minWidth: 140
        },
        {
          title: '发卡馆',
          key: 'storeId',
          minWidth: 140,
          render: (h, params) => {
            for (let i of this.storeIdList) {
              if (params.row.storeId === i.id) {
                return h(
                  'span',
                  {},
                  i.storeName
                )
              }
            }
          }
        },
        {
          title: '卡名称',
          key: 'cardName',
          minWidth: 140
        },
        {
          title: '消费金额',
          key: 'money',
          minWidth: 100
        },
        {
          title: '累计消费',
          key: 'total',
          minWidth: 100
        },
        {
          title: '操作人',
          key: 'action',
          minWidth: 100
        },
        {
          title: '时间',
          key: 'createTime',
          minWidth: 140,
          render: (h, params) => {
            return h('span', {
              style: {
              }
            }, formatDateTime(params.row.createTime))
          }
        },
        {
          title: '备注',
          key: 'remarks',
          minWidth: 200
        },
        {
          title: '操作',
          key: 'action',
          width: 150,
          fixed: 'right',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.detailsModal = true
                    this.$refs.detailsModal.getByPhone(params.row.phone)
                  }
                }
              }, '详情'),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                on: {
                  click: () => {
                    this.deleteExpense(params.row.id)
                  }
                }
              }, '删除')
            ])
          }
        }
      ],
      expenseColumns: [],
      // 筛选条件
      formSearch: {
        cardName: '',
        size: 20,
        page: 1,
        member: '',
        storeId: 0,
        moneyMin: '',
        moneyMax: ''
      },
      model13: '',
      loading1: false,
      options1: [],
      list: [],
      reseIndex: 0,
      startValue: '',
      endValue: ''
    }
  },
  filters: {
    cardTypeUt (val) {
      switch (val) {
        case 1:
          return '天'
        case 2:
          return '次'
        case 3:
          return '元'
      }
    }
  },
  computed: {
    formatStartNumber () {
      if (this.startValue === '') return '请输入金额'
      function parseNumber (str) {
        const re = /\d{1,3}(?=(\d{3})+(\.|$))/g
        return str.replace(re, '$&,')
      }
      return parseNumber(this.startValue)
    },
    formatEndNumber () {
      if (this.endValue === '') return '请输入金额'
      function parseNumber (str) {
        const re = /\d{1,3}(?=(\d{3})+(\.|$))/g
        return str.replace(re, '$&,')
      }
      return parseNumber(this.endValue)
    },
    ...mapGetters([
      'userInfo'
    ])
  },
  async created () {
    if (this.userInfo.storeId) {
      this.$set(this.expense, 'storeId', this.userInfo.storeId)
      this.$set(this.formSearch, 'storeId', this.userInfo.storeId)
    }
    this.tableLoading = true
    await this.cardList()
    await this.storeAll()
    await this.expenseList()
  },
  methods: {
    storeAll () { // 场馆列表
      return new Promise((resolve, reject) => {
        storeAll().then(res => {
          this.storeIdList = res.data
          resolve(res.data)
        })
      })
    },
    cardList () { // 卡列表
      cardList({
        name: '',
        type: '',
        varieties: ''
      }).then(res => {
        this.cardNameList = res.data
        res.data.forEach(e => {
          this.cardNameObj['card' + e.id] = e
        })
      })
    },
    expenseList () {
      this.tableLoading = true
      this.formSearch.storeId = this.formSearch.storeId || 0
      expenseList(this.formSearch).then(res => {
        this.expenseColumns = res.data.rows
        this.pageTotal = res.data.total
        this.tableLoading = false
      })
    },
    onAddExpenseVisible (visible) {
      // 弹框状态改变 清除默认值
      if (visible) return
      this.$refs['expenseForm'].resetFields()
    },
    onExpenseSubmit () {
      this.$refs['expenseForm'].validate(valid => {
        // eslint-disable-next-line no-useless-return
        setTimeout(() => {
          this.loading = false
        }, 300)
        setTimeout(() => {
          this.loading = true
        }, 400)
        if (!valid) return
        addExpense(this.expense).then(res => {
          this.$refs['expenseForm'].resetFields()
          this.expenseModal = false
          this.$Message.success('添加成功')
          this.expenseList()
        })
      })
    },
    deleteExpense (id) {
      this.$Modal.confirm({
        title: '提示',
        content: '确定删除？',
        loading: true,
        okText: '删除',
        onOk: () => {
          deleteExpense(id)
            .then(res => {
              this.$Modal.remove()
              this.$Message.success('删除成功')
              this.expenseList()
            })
            .catch(() => {
              this.$Modal.remove()
            })
        }
      })
    },
    remoteMethod1 (query) {
      if (query !== '') {
        this.loading1 = true
        setTimeout(() => {
          this.loading1 = false
          const cardNameList = this.cardNameList.map(item => {
            return {
              value: item.id,
              label: item.name
            }
          })
          this.options1 = cardNameList.filter(item => item.label.toLowerCase().indexOf(query.toLowerCase()) > -1)
        }, 200)
      } else {
        this.options2 = []
      }
    },
    getByPhone (val) {
      this.seachText = '正在查询...'
      getByPhone(val).then(res => {
        this.seachText = res.data.realname
        // this.seachInfoCards = res.data.cards
        getMemberCard(res.data.memberId).then(res => {
          //   this.cardNameList = res.data
          res.data.forEach(e => {
            this.myCardNameObj['card' + e.id] = e
          })
          this.seachInfoCards = res.data
        }).catch(() => {

        })
      }).catch(() => {
        this.seachText = '查询失败'
      })
    },
    exportExpense () { // 导出数据
      const { cardName, storeId, member, moneyMin, moneyMax } = this.formSearch
      exportExpense({
        page: 1,
        storeId: storeId,
        size: this.pageTotal,
        member: member,
        cardName: cardName,
        moneyMin: moneyMin,
        moneyMax: moneyMax
      }).then(res => {
        const link = document.createElement('a')
        let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        console.log(res.headers['content-disposition'])
        // link.download = res.headers['content-disposition'].match(/filename=(\S*)/)[1] // 下载后文件名
        link.download = '消费数据.xls'// 下载的文件名
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)

        this.$Message.success('导出成功')
      })
    },
    changeCardType (item) {
      const type = this.myCardNameObj['card' + item].type
      this.$set(this.expense, 'consumptionType', type)
    },
    changePage (val) {
      this.formSearch = { ...this.formSearch, page: val }
      this.expenseList()
    }
  }
}
</script>
<style lang="less">
.sellPending {
  flex: 1;
  .search-item {
    display: flex;
    margin-bottom: 10px;
    .search-btn {
      margin-left: 20px;
    }
  }
}
.receiverTypeTip {
  text-align: center;
  overflow: hidden;
  &-title {
    margin-bottom: 5px;
  }
  &-img {
    width: 200px;
    overflow: hidden;
    img {
      width: 100%;
      height: auto;
    }
  }
}
.confirmRemberModalRow {
  margin-bottom: 10px;
}
.loading-drop-down {
  display: flex;
  align-items: center;
  padding: 2px 16px;
  background-color: #f2f6fa;
  color: #357ce1;
  border-radius: 2px;
}
</style>
